// 导入 MySQL 包
const mysql = require("mysql");
// 创建数据库连接对象
const connection = mysql.createPool({
  host: "localhost",
  user: "root",
  password: "123456",
  database: "test",
  connectionLimit: 10,
});
// 打开连接

// 执行查询语句
connection.query("SELECT * from score", function (error, results, fields) {
  if (error) throw error;
  console.log("The solution is: ", results);

  connection.query("SELECT * from score", function (error, results, fields) {
    if (error) throw error;
    console.log("The solution is: ", results);
    // 关闭连接
    connection.end((err) => {
      console.log("数据库已经关闭");
    });
  });
});

class MySql {
  constructor(config) {
    this.pool = mysql.createPool(config);
  }
  query(sql, values) {
    return new Promise((resolve, reject) => {
      this.pool.query(sql, values, (error, results, fields) => {
        if (error) return reject(error);
        resolve([results, fields]);
      });
    });
  }
  close() {
    return new Promise((resolve, reject) => {
      this.pool.end((err) => {
        if (err) return reject(err);
        resolve();
      });
    });
  }
}

(async () => {
  const db = new MySql({ user: "root", password: "123456", database: "test" });
  const [results] = await db.query("select * from score");
  console.log(results);
  await db.close();
})();
